<?php
/**
 * FastApp.
 * 3/28/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Hoenix\Api\Service;

use App\Fastapp\Exception\TipException;
use App\Hoenix\Job\IndexKeywordJob;
use App\Hoenix\Model\HoenixIndex;
use App\Hoenix\Model\HoenixKeyword;

class SeedService
{
    public static function search(string $kw, int $page, int $type, array $def = []): array
    {
        if (mb_strlen($kw) == 1 && (is_numeric($kw) || ctype_alpha($kw) || preg_match('/[\x{3000}-\x{303F}\x{FF00}-\x{FFEF}\x{0020}-\x{002F}\x{003A}-\x{0040}\x{005B}-\x{0060}\x{007B}-\x{007E}]/u', $kw))) return $def;
        $words = [];
        if ($kw) {
            $keywds = 'h:segment:' . md5($kw);
            $words = cache()->get($keywds);
            if (!$words) {
                $cmd = 'python3 ' . dirname(BASE_PATH) . '/py/cut.py ';
                exec($cmd . "'" . $kw . "'", $output);
                $words = array_filter(json_decode($output[0], true));
                if (!$words) return ['没有找到相关信息！', ''];
                cache()->set($keywds, $words, 86400);
            }
        }
        $keydata = 'h:search:' . md5($kw . $page . $type);
        $keytotal = 'h:total:' . md5($kw);
        $list = cache()->get($keydata);
        if ($list) {
            $total = cache()->get($keytotal);
        } else {
            if ($words) {
                $query = HoenixKeyword::query()
                    ->selectRaw('c.*')
                    ->join('hoenix_keyword_index as b', 'b.kid', '=', 'hoenix_keyword.id')
                    ->join('hoenix_index as c', 'c.id', '=', 'b.idx')
                    ->whereIn('kw', $words);
            } else {
                $query = HoenixIndex::query()->orderByDesc('sort');
            }
            if ($type) $query->where(['type' => $type]);
            $total = $query->count();
            cache()->set($keytotal, $total, 1801);
            if ($total) {
                $list = $query->simplePaginate(page: $page)->items();
                cache()->set($keydata, $list, 1800);
            }
            if (!$list) $list = [];
        }
        return ['total' => $total, 'list' => $list];
    }

    public function addCloudResources(string $title, string $desc): bool
    {
        $pattern = '/https?:\/\/(?:pan\.baidu\.com|www\.aliyundrive\.com|pan\.quark\.cn|www\.123pan\.com)\/[^\s\/]\S*/i';
        preg_match($pattern, $desc, $matches);
        $url = $matches[0] ?? '';
        if (!$url) throw new TipException('不是一个有效网盘链接');
        fastapp_queue_push(new IndexKeywordJob(['url' => $url, 'type' => 8, 'title' => $title, 'desc' => $desc]), 'hoenix');
        return true;
    }
}